<template>
  <UploadExcel :before-upload="beforeUpload" :on-success="onSuccess" />
</template>

<script>
import { addBatchEmployeeList } from '@/api/employee'
export default {
  methods: {
    beforeUpload(rawFile) {
      if (rawFile.size > 2 * 1024 * 1024) {
        this.$message.error('上传的文件超出限制大小')
        return false
      } else {
        return true
      }
    },
    async onSuccess(excelData) {
      const arr = excelData.results.map(item => {
        return this.transferEn(item)
      })
      await addBatchEmployeeList(arr)
      this.$message.success('新增成功')
      //   页面跳转
      this.$router.back()
    },
    transferEn(user) {
      const newUser = {}
      // 如果是导入员工
      const dict = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      for (const key in user) {
        // 英文键
        const enkey = dict[key]
        // 取value值
        const value = user[key]
        if (enkey === 'correctionTime' || enkey === 'timeOfEntry') {
          newUser[enkey] = new Date(this.formatDateExcel(value))
        } else {
          newUser[enkey] = value
        }
      }
      return newUser
    },
    // 格式化时间
    formatDateExcel(num, format = '-') {
      num = Number(num)	// 强制类型转化，以防传来的值是字符串
      let millisecond = 0	// 转化后的毫秒数
      if (num > 60) {
        millisecond = (num - 25569) * 60 * 60 * 24 * 1000
      } else {
        millisecond = (num - 25568) * 60 * 60 * 24 * 1000
      }
      const date = new Date(millisecond)	// 根据转化后的毫秒数获取对应的时间
      const yy = date.getFullYear()
      const mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      return yy + format + mm + format + dd	// 返回格式化后的日期
    }
  }
}
</script>

<style>

</style>
